<template>
  <div class="wrapper">
    <div class="loginBox">
      <h1>生产结算系统</h1>
      <div class="loginForm">
        <el-form :model="form" label-width="auto" :rules="rules" ref="formRef" style="max-width: 600px" >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" type="text"/>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" type="password"/>
          </el-form-item>
        </el-form>
      </div>
      <el-button class="loginBtn" type="primary" @click="loginHandler(formRef)">登录</el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { userInfoStore } from '@/store/userInfoStore'

// 表单
const formRef = ref(null);
const form = reactive({
  username: '',
  password: ''
})
const validateFn = (rule, value, callback)=>{
  if (value === '') {
    callback(new Error('请输入用户名称'));
  } else if (/\s/.test(value)) { // 检查是否包含空格
    callback(new Error('用户名称不能使用空格'));
  } 
  else {
    callback();
  }
}
const rules = reactive({
  username: [
    { validator: validateFn, required: true, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
  ]
})


// 路由+store+登录
const router = useRouter();
const userInfo = userInfoStore();

const loginHandler = async (formEl) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      // 获取token
      await userInfo.getTokens({username: form.username, password: form.password})
      // 应该跳转到一个静态页面上 而不是一个动态添加的页面上 避免出现第一次跳转时出现动态路由未添加的状态
      router.push('/welcome')
    }
  })

}

</script>
<style lang="scss" scoped>
.wrapper{
  display: flex;
  justify-content: center;
  align-items: center;

  width: 100%;
  height: 100%;
  
  background-image: url('@/assets/windows-11-green-3840x2160-16013.jpg');
  background-size: cover;  /* 图片等比缩放，覆盖整个容器 */
  background-position: center;  /* 居中显示，避免边缘被裁剪 */
  background-repeat: no-repeat;  /* 不重复 */

  .loginBox{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center; /* 垂直居中 */
    width: 500px;
    height: 500px;
    opacity: 0.9;
    background-color: #F5F5F5;
    border-radius: 30px;

    h1 {
      color: #333; /* 设置文本颜色 */
      font-size: 24px; /* 设置字体大小 */
      text-align: center; /* 居中对齐 */
    }

    .loginBtn{
      width: 180px;
    }
  }
}

</style>